$('#data-tab').fadeIn();
totalShares($URL);

// Format Number functions
function ReplaceNumberWithCommas(yourNumber) {
  //Seperates the components of the number
  var components = yourNumber.toString().split(".");
  //Comma-fies the first part
  components[0] = components[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  //Combines the two sections
  return components.join(".");
}

// SHARE COUNTS FUNCTIONS 

// Facebook Shares Count
function facebookShares($URL) {
  $.getJSON('http://graph.facebook.com/?id=' + $URL, function (fbdata) {
   // $('#facebook-count').text(ReplaceNumberWithCommas(fbdata.shares))
    $('#facebook-count').attr('data-hover', fbdata.shares);
    $('#total-shares').attr('data-facebookShares', fbdata.shares)
  });
}

// Twitter Shares Count
function twitterShares($URL) {
  $.getJSON('http://cdn.api.twitter.com/1/urls/count.json?url=' + $URL + '&callback=?', function (twitdata) {
   // $('#twitter-count').text( ReplaceNumberWithCommas(twitdata.count))
    $('#twitter-count').attr('data-hover', twitdata.count);
    $('#total-shares').attr('data-twitterShares', twitdata.count)
  });
}

// LinkIn Shares Count
function linkedInShares($URL) {
  $.getJSON('http://www.linkedin.com/countserv/count/share?url=' + $URL + '&callback=?', function (linkedindata) {
    //$('#linkedin-count').text(ReplaceNumberWithCommas(linkedindata.count) )
    $('#linkedin-count').attr('data-hover', linkedindata.count);
    $('#total-shares').attr('data-linkedInShares', linkedindata.count)
  });
}

// Check if all JSON calls are finished or not

function checkJSON_getSum() {
  if ($('#total-shares').attr('data-facebookShares') != undefined && $('#total-shares').attr('data-twitterShares') != undefined && $('#total-shares').attr('data-linkedinshares') != undefined) {

    console.log('All JSON calls are finished .. getting total sum!')
    
    var fbShares = parseInt($('#total-shares').attr('data-facebookShares'));
    var twitShares = parseInt($('#total-shares').attr('data-twitterShares'));
    var linkedInShares = parseInt($('#total-shares').attr('data-linkedinshares'));
    var totalShares = fbShares + twitShares + linkedInShares;
    console.log(totalShares);
    $('#total-count').text(ReplaceNumberWithCommas(totalShares) + ' shares')

  }
  // Check for JSON again!
  else {
    setTimeout(function () {
      checkJSON_getSum();
    }, 200);
  }

}

function totalShares($URL) {
  linkedInShares($URL);
  twitterShares($URL);
  facebookShares($URL);
  checkJSON_getSum();
}